package ro.myApp.client;

import java.io.Serializable;

import javax.ejb.EJB;
import javax.naming.InitialContext;
import javax.naming.NamingException;

import org.jboss.seam.Component;
import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.AutoCreate;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Logger;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Scope;
import org.jboss.seam.annotations.Startup;
import org.jboss.seam.contexts.Contexts;
import org.jboss.seam.faces.FacesMessages;
import org.jboss.seam.international.StatusMessage.Severity;
import org.jboss.seam.log.Log;
import org.jboss.seam.security.Credentials;

import ro.myApp.commons.dto.BaseDtoMessage;
import ro.myApp.commons.service.EsbService;
import ro.myApp.commons.service.exceptions.ViewException;

@Name("sessionController")
@Scope(ScopeType.SESSION)
@AutoCreate
@Startup
public class SessionController implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 2622989276691206863L;

	@Logger
	private Log log;
	
	@In
	private Credentials credentials;
	
	@EJB
	private EsbService esb;

	public static SessionController instance() {
		if (!Contexts.isSessionContextActive()) {
			throw new IllegalStateException("No active session context");
		}
		SessionController instance = (SessionController) Component.getInstance(
				SessionController.class, ScopeType.SESSION);
		if (instance == null){
			throw new IllegalStateException("No SessionController could be created");
		}
		return instance;
	}

	public Object sendMessage(BaseDtoMessage msg) {
		if (null == esb) {
			log.warn("esb was not correctly injected in session. will try lookup");
			esb = (EsbService) getEJB("EsbServiceImpl");
		}
		try {
			msg.setUserName(credentials.getUsername());
			return esb.sendMessageSynchronous(msg);
		} catch (ViewException ve) {
			log.info("This is a treated exception.");
			FacesMessages.instance().addFromResourceBundle(Severity.ERROR, ve.getKey());
			throw ve;
		} catch (Throwable e) {
			log.error("Unexpected exception occured.", e);
			throw new RuntimeException(e);
		}
	}

	private Object getEJB(String ejbName) {
		Object jh = null;
		try {
			jh = new InitialContext().lookup(ejbName + "/remote");
		} catch (NamingException e) {
			e.printStackTrace();
		}
		return jh;
	}
}
